﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Espam.Idiomas.Decimo.Tesis.Negocio;
using Microsoft.Reporting.WebForms;

namespace Espam.Idiomas.Decimo.Tesis.Web
{
    public partial class UI_GraduatesReport : System.Web.UI.Page
    {
        string validaSession = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
                Response.Cache.SetAllowResponseInBrowserHistory(false);
                Response.Cache.SetNoStore();

                if (Session["userEspamIdiomasVarSession001"] == null || Session["rolEspamIdiomasVarSession003"] == null)
                {
                    validaSession = "NoHaIniciadoSession";
                    Response.Redirect("UI_Login.aspx?validaSession=" + validaSession);
                }
                else if (Session["userEspamIdiomasVarSession001"] != null && Session["rolEspamIdiomasVarSession003"].ToString() == "Docente")
                {
                    Response.Redirect("UI_DashboardTeacher.aspx");
                }
                else if (Session["userEspamIdiomasVarSession001"] != null && Session["rolEspamIdiomasVarSession003"].ToString() == "Administradores")
                {

                    MaintainScrollPositionOnPostBack = true;
                    CargarCarreras();
                    ddlCarreras.AutoPostBack = true;
                  //  btnGenerarReporte.Attributes.Add("onclick", " this.disabled = true,this.value='Procesando...'; " + ClientScript.GetPostBackEventReference(btnGenerarReporte, null) + ";");

                }
                else if (Session["userEspamIdiomasVarSession001"] != null && Session["rolEspamIdiomasVarSession003"].ToString() == "Alumno")
                {
                    Response.Redirect("UI_DashboardStudents.aspx");
                }
            }
            else
            {
                MaintainScrollPositionOnPostBack = true;
            }
        }
        private void CargarCarreras()
        {
            ListadoCarreras oLista = new ListadoCarreras();
            List<Carreras> lista = new List<Carreras>();
            lista = oLista.GetCarreras();
            lista.Insert(0, new Carreras() { idCarreras=0,carrera="<seleccione>"});
            ddlCarreras.DataSource=lista;
            ddlCarreras.DataTextField = "carrera";
            ddlCarreras.DataValueField = "idCarreras";
            ddlCarreras.DataBind();
        }
        private void cargarGrid()
        {
            Usuarios oUsuarios = new Usuarios();
            List<Usuarios> lista = new List<Usuarios>();
            oUsuarios.idCarrera = int.Parse(ddlCarreras.SelectedValue);
            lista=oUsuarios.GetEgresadosCompleto();
            if (lista.Count>0)
            {
                gvDocentes.DataSource = lista;
                gvDocentes.DataBind();
                if (gvDocentes.Rows.Count > 0)
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Dttable", String.Format("CargaDataTable('{0}',{1});", "Contenido_gvDocentes", gvDocentes.Rows[0].Cells.Count), true);
                btnGenerarReporte.Text = "Exportar a pdf";
            }
            else
            {
                gvDocentes.DataSource = lista;
                gvDocentes.DataBind();
                btnGenerarReporte.Text = "Generar Reporte";
            }
        }

        protected void btnGenerarReporte_Click(object sender, EventArgs e)
        {
            if (btnGenerarReporte.Text=="Generar Reporte")
            {
                cargarGrid();

            }
            else
            {
                btnGenerarReporte.Text = "Generar Reporte";
                CrearReporte();
            }
            
        }
        private void CrearReporte()
        {
            Usuarios oUsu = new Usuarios();

            //EspamIdiomasDataSet.sp_getDocentesDataTable dt = new EspamIdiomasDataSet.sp_getDocentesDataTable();
            //EspamIdiomasDataSetTableAdapters.sp_getDocentesTableAdapter da = new EspamIdiomasDataSetTableAdapters.sp_getDocentesTableAdapter();
            //da.Fill(dt, ddlGenero.SelectedValue);
            EspamIdiomasDataSet.sp_egresadosPivotDataTable dt = new EspamIdiomasDataSet.sp_egresadosPivotDataTable();
            EspamIdiomasDataSetTableAdapters.sp_egresadosPivotTableAdapter da = new EspamIdiomasDataSetTableAdapters.sp_egresadosPivotTableAdapter();
            da.Fill(dt, int.Parse(ddlCarreras.SelectedValue));

            ReportViewer viewer = new ReportViewer();
            ReportDataSource RD = new ReportDataSource();
            RD.Value = dt;
            RD.Name = "DataSet1";
            //viewer.LocalReport.ReportPath = Server.MapPath("Reports/Administradores/Egresados.rdlc");
            viewer.LocalReport.DataSources.Clear();
            viewer.LocalReport.DataSources.Add(RD);
            //viewer.LocalReport.ReportEmbeddedResource = "Egresados.rdlc";
            viewer.LocalReport.ReportPath = Server.MapPath("Reports/Administradores/Egresados.rdlc");
            viewer.LocalReport.Refresh();

            string mimeType;
            string encoding;
            string fileNameExtension;
            string[] streams;
            Warning[] warnings;
            byte[] pdfContent = viewer.LocalReport.Render("PDF", string.Empty, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);

            this.Response.Clear();
            this.Response.ContentType = "application/pdf";
            this.Response.AddHeader("Content-disposition", "attachment; filename=Egresados.pdf");
            this.Response.BinaryWrite(pdfContent);
            this.Response.End();

        }

        protected void ddlCarreras_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnGenerarReporte.Text = "Generar Reporte";
            cargarGrid();
        }

        protected void gvDocentes_Load(object sender, EventArgs e)
        {
            if (gvDocentes.Rows.Count > 0)
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Dttable", String.Format("CargaDataTable('{0}',{1});", "Contenido_gvDocentes", gvDocentes.Rows[0].Cells.Count), true);
        }

        protected void gvDocentes_PreRender(object sender, EventArgs e)
        {
            GridView gvDocentes = (sender) as GridView;
            if (gvDocentes.Rows.Count > 0)
            {
                //This replaces <td> with <th> and adds the scope attribute
                gvDocentes.UseAccessibleHeader = true;

                //This will add the <thead> and <tbody> elements
                gvDocentes.HeaderRow.TableSection = TableRowSection.TableHeader;

                //This adds the <tfoot> element. 
                //Remove if you don't have a footer row
                gvDocentes.FooterRow.TableSection = TableRowSection.TableFooter;
            }
        }
    }
}